从数组属性获取元素。我得到了正确的答案,为什么它不接受?


function getElementOfArrayProperty(obj, key, index) {

for(var i in obj) {
if(obj[i].length === 0 || !Array.isArray(obj[i])) {
return undefined;
}

for(var y = 0; y < obj[i].length; y++) {
if(!obj[key][index]) {
return undefined;
}
if(obj[i][y] === obj[key][index]) {
return obj[key][index];
}

}
}
}
var obj = {
key: ['Jamil', 'Albrey']
};
var output = getElementOfArrayProperty(obj, 'key', 0);
console.log(output); // --> 'Jamil'

以下是这个问题的标准-

X( 应在传入对象的键处返回数组索引处的元素

✓ should return undefined if the index is out of range
✓ should return undefined if the property at the key is not an array
✓ should return undefined if there is no property at the key

我会按照要求返回"Jamil",为什么它不喜欢我的输出?有什么是我概念上没有理解的吗?还是这项运动被窃听了?

试试这个:

  1. 如果obj没有key,或者obj[key]不是array,或者index无效=>返回undefined
  2. 否则,参数是有效的,因此,返回obj[key][index]

function getElementOfArrayProperty(obj, key, index) {
if(!obj[key] || !Array.isArray(obj[key]) || index < 0 || index >= obj[key].length)
return undefined;
return obj[key][index];
}
const obj = { key: ['Jamil', 'Albrey'], key1: 'str' };
console.log( 'obj, key, 0 => ',  getElementOfArrayProperty(obj, 'key', 0) );
console.log( 'obj, key, 2 => ',  getElementOfArrayProperty(obj, 'key', 2) );
console.log( 'obj, key, -1 => ', getElementOfArrayProperty(obj, 'key', -1) );
console.log( 'obj, key1, 0 => ', getElementOfArrayProperty(obj, 'key1', 0) );
console.log( 'obj, key2, 0 => ', getElementOfArrayProperty(obj, 'key2', 0) );

在对象的条目上使用Array.find

function getElementOfArrayProperty(obj, key, index) {
const maybeFoundIt = Object.entries(obj)
.find(([xkey, value]) => xkey === key &&
Array.isArray(value) &&
value.length &&
+index > -1 &&
index < value.length);
// return the value if something was found, otherwise undefined    
return maybeFoundIt ? maybeFoundIt[1][index] : undefined;
}
const obj = {
key: ['Jamil', 'Albrey'],
notArray: {
x: 1
},
};
const yepNope = isOk => isOk ? "✓" : "X";
console.log(`should return undefined if the index is out of range: ${
yepNope(!getElementOfArrayProperty(obj, 'key', 24))}`);
console.log(`**should return undefined if no index is given: ${
yepNope(!getElementOfArrayProperty(obj, 'key'))}`);
console.log(`should return undefined if the property at the key is not an array: ${
yepNope(!getElementOfArrayProperty(obj, 'notArray', 0))}`);
console.log(`should return undefined if there is no property at the key: ${
yepNope(!getElementOfArrayProperty(obj, 'dontknowthis', 0))}`);
console.log(`otherwise returns a value: ${
yepNope(getElementOfArrayProperty(obj, 'key', 0))}`);

最新更新