我正在处理以下练习问题,但我一直在收到错误。
题: 编写一个名为“getElementOfArrayProperty”的函数。
给定一个对象,一个键和一个数字索引,“getElementOfArrayProperty”返回位于给定键处给定对象内的数组的给定索引处元素的值。
笔记: *如果数组是空的,它应该返回undefined。 *如果给定索引超出位于给定键的数组的范围,则它应该返回undefined。 *如果给定键的属性不是数组,则它应该返回undefined。 *如果在键上没有属性,它应该返回undefined。
function getElementOfArrayProperty(obj, key, index) { var element = ''; if (!obj[key] || !obj[key][index] || Array.isArray(obj[key]) === false) { return undefined; } else { for (var i = 0; i < obj[key].length; i ++) { element = obj[key][index]; } } return element; } var obj = { key: ['Jamil', 'Albrey', 'jones', 'justin'] }; getElementOfArrayProperty(obj, 'key', 3);我的代码返回正确的索引值,但我不断收到以下错误:
should_return_the_element_at_the_index_of_the_array_at_the_key_of_the_passed_in_object应该在传入的对象的键的数组索引处返回元素
预计未定义为0。
任何人都可以看到发生了什么?
I am working on the following practice problem but I keep getting an error.
Question: Write a function called "getElementOfArrayProperty".
Given an object, a key, and a numerical index, "getElementOfArrayProperty" returns the value of the element at the given index of the array located within the given object at the given key.
Notes: * If the array is empty, it should return undefined. * If the given index is out of range of the array located at the given key, it should return undefined. * If the property at the given key is not an array, it should return undefined. * If there is no property at the key, it should return undefined.
function getElementOfArrayProperty(obj, key, index) { var element = ''; if (!obj[key] || !obj[key][index] || Array.isArray(obj[key]) === false) { return undefined; } else { for (var i = 0; i < obj[key].length; i ++) { element = obj[key][index]; } } return element; } var obj = { key: ['Jamil', 'Albrey', 'jones', 'justin'] }; getElementOfArrayProperty(obj, 'key', 3);My code returns the correct index value but I keep getting the following error:
should_return_the_element_at_the_index_of_the_array_at_the_key_of_the_passed_in_object should return the element at the index of the array at the key of the passed in object
Expected undefined to be 0.
Can anyone see what's going on?
最满意答案
我的猜测是这个代码是问题!obj[key][index] 。 从我所看到的,它期望为0 。 有问题的代码会将值0视为false ,然后使其返回undefined 。
更改该代码以显式检查null和undefined值
obj[key][index] == nullMy guess is this code is the issue !obj[key][index]. From what i can see, it is expecting 0. The offending code will treat a value of 0 as false and then cause it to return undefined.
Change that code to explicitly check for null and undefined values
obj[key][index] == null更多推荐
发布评论