[英]Why does this not return an array containing all but the last element of of an array located at a given key
這是問題所在:
給定一個對象和一個鍵,編寫一個函數,該函數返回一個數組,該數組包含位於給定鍵處的數組的最后一個元素。
筆記:
我的代碼:
var obj = {
key: [1, 2, 3]
};
function getAllButLastElementOfProperty(obj, key) {
var arr = []
arr = obj.key.pop()
return obj.key
}
getAllButLastElementOfProperty(obj, 'key') // [1, 2]
題:
為什么它不能使每個repl測試失敗,包括提示“應該返回一個數組,該數組包含位於key處的數組的最后一個元素以外的所有元素”?
無論您在function getAllButLastElementOfProperty(obj, key)
為key
參數輸入什么內容, function getAllButLastElementOfProperty(obj, key)
每次運行時都在尋找key
屬性。
嘗試像這樣修改它:
var test_obj = {
key: [1, 2, 3],
banana: [3,2,1],
};
function getAllButLastElementOfProperty(obj, key) {
var new_obj = obj;
new_obj[key].pop()
return new_obj[key];
}
console.log(getAllButLastElementOfProperty(test_obj, 'banana')) // [1, 2]
這將利用函數中的key
參數作為obj
的屬性。
編輯:我實際上將使用以下函數,以便它不會修改原始對象( test_obj
):
function getAllButLastElementOfProperty(obj, key) {
var arr = obj[key].slice(0); // Duplicate array without modifying original in test_obj
arr.pop(); // remove last element
return arr;
}
這是您可以執行的操作,驗證鍵處的值是否為Array,然后繼續從數組中刪除最后一個元素。 希望這可以幫助。
var obj = { key: [1, 2, 3], newKey: [4, 5], singleValue: [1], emptyArray: [], objectKey: {} }; function getAllButLastElementOfProperty(obj, key) { var arr = [], objectAtKey = obj[key]; if (Array.isArray(objectAtKey)) { arr = objectAtKey.slice(0, objectAtKey.length - 1); } return arr; } console.log(getAllButLastElementOfProperty(obj, 'key')); console.log(getAllButLastElementOfProperty(obj, 'newKey')); console.log(getAllButLastElementOfProperty(obj, 'singleValue')); console.log(getAllButLastElementOfProperty(obj, 'emptyArray')); console.log(getAllButLastElementOfProperty(obj, 'objectArr')); console.log(getAllButLastElementOfProperty(obj, 'nonExistentKey'));
有一個pop()
的用法。 此方法刪除 使用的數組的最后一個值。 每次運行此方法時,它會將數組縮短一倍。 因此,請使用Array.prototype.slice() 。 它不會改變數組。
使用Array.isArray()測試該項是否為數組:
if(!Array.isArray(item)) { return []; }
總共
var obj = { key: [1, 2, 3] }; function getAllButLastElementOfProperty(obj, key) { if (!Array.isArray(obj.key)) { return []; } var res = [], arr = obj.key; res = arr.slice(0, (arr.length - 1)); // slice() doesn't change the used array return res; } console.log(getAllButLastElementOfProperty(obj, "key")); console.log(getAllButLastElementOfProperty(obj, "key")); console.log(getAllButLastElementOfProperty(obj, "key")); console.log(getAllButLastElementOfProperty(obj, "key"));
var obj = {
key: [1, 2, 3]
};
function getAllButLastElementOfProperty(obj, key) {
if(obj.key.length < 1 || !Array.isArray(obj.key) || !obj.hasOwnProperty(key)) {
return [];
}
var newObj = obj.key.slice(0, obj.key.length - 1);
return newObj;
}
var output = getAllButLastElementOfProperty(obj, 'key');
output;
我有相同的問題...這可以正確運行,但是由於某種原因,我得到了相同的失敗測試:“ TypeError:無法讀取所有測試的屬性'length'of undefined”。 我將嘗試使用最新的解決方案,但有些人可以告訴我為什么會引發該錯誤嗎? 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.