[英]Problem with comparing an Array with an object
是的,這是作業,我不想作弊,我想弄清楚我做錯了什么:)“當我有一個“未定義”的值時,我到底需要做什么?
編寫一個函數 compare 接受一個數組和一個對象,如果所有數組值都作為對象值存在,則返回 true。 請注意:我的導師不希望學生使用任何花哨的快捷方式,例如 Object.values(object) 這是我目前的代碼:
const compare = function (array, object) {
let i = 0;
while(i<array.length){
for(const key in object){
if(array[i] == object[key]) {
console.log("Array val: "+array[i] + " " + "Object val: "+object[key])
i++
}
else if(array[i] !== object[key]){
console.log("Array val: "+array[i] + " " + "Object val: "+object[key])
return false
}
}
}
return true
}
compare(["one", "two", "three"], { 0: "one", 1: "two", 2: "three" }); // => true
compare(["one", "two", "four"], { 0: "one", 1: "two", 2: "three" }); // => false
compare(["one", "two"], { foo: "one", bar: "two", baz: "three" }); // => true
compare(["one", "two", "three"], { foo: "one", bar: "two" }); // => false
當我有一個“未定義”的值時,我到底需要做什么?
這樣做(O(n)):
function compare(arr, obj) {
const set = new Set(Object.values(obj));
return arr.every(v => set.has(v));
}
console.log(compare(["one", "two", "three"], { 0: "one", 1: "two", 2: "three" }));// => true
console.log(compare(["one", "two", "four"], { 0: "one", 1: "two", 2: "three" }));// => false
console.log(compare(["one", "two"], { foo: "one", bar: "two", baz: "three" }));// => true
console.log(compare(["one", "two", "three"], { foo: "one", bar: "two" }));// => false
如果您需要做舊學校(仍然是 O(n)),我建議這樣做:
function compare(arr, obj) {
const set = {};
for (const key in obj) {
set[obj[key]] = true;
}
/* for loop works too
for (let i = 0; i < arr.length; i++) {
if (!set[arr[i]]) {
return false;
}
}
*/
while (arr.length) {
if (!set[arr.pop()]) {
return false;
}
}
return true;
}
console.log(compare(["one", "two", "three"], { 0: "one", 1: "two", 2: "three" }));// => true
console.log(compare(["one", "two", "four"], { 0: "one", 1: "two", 2: "three" }));// => false
console.log(compare(["one", "two"], { foo: "one", bar: "two", baz: "three" }));// => true
console.log(compare(["one", "two", "three"], { foo: "one", bar: "two" }));// => false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.