我想知道这条线上发生了什么,我用粗体。我知道他们的工作,但我不知道为什么。 [英] I'd like to know what's happening in the line's I've bolded. I know they 'work, ' but I'm not sure why.
问题描述
我正在锻炼,我必须编写一个名为select的函数。给定一个数组和对象,我不得不返回一个新对象,其属性仅包括数组和原始对象中常见的对象。例如:
I was doing in exercise in which I had to write a function called select. Given an array and object, I had to return a new object whose properties included only those which were common among the array and the original object. For example:
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
下面的代码有效,但我正在努力理解newObject [search] = obj [search]如何在newObject中产生正确的结果。
The code below 'works,' but I'm trying to understand how newObject[search] = obj[search] yields the right results in newObject.
function select(arr, obj) {
var newObject = {};
var keys = Object.keys(obj);
for (var i = 0; i < arr.length; i++) {
var search = arr[i];
if (keys.indexOf(search) !== - 1) {
newObject[search] = obj[search];
}
}
return newObject;
}
我的尝试:
我已经多次通过Google开发工具中的调试器运行此代码。我最好的理解是obj [search]一直回到'keys'变量,以找出它与'search'变量的关系。
真诚地感谢您的帮助!
What I have tried:
I've run this code through the debugger in Google dev tools multiple times. My best understanding is that obj[search] reaches all the way back up to the 'keys' variable to find out how it relates to the 'search' variable.
Thanks sincerely for your help!
推荐答案
function select(arr, obj) {
var newObject = {};
var keys = Object.keys(obj);
for (var i = 0; i < arr.length; i++) {
var search = arr[i];
if (keys.indexOf(search) !== - 1) {
newObject[search] = obj[search];
}
}
return newObject;
}
您正在设置的变量包含 obj
参数的所有键 - 键
。然后迭代遍历 arr
参数,检查每个元素( search
)是否在键中
list( indexOf
如果未找到密钥则返回-1)。如果元素在列表中,则将值从 obj
移动到 newObject
。
给出你的例子的赋值语句将执行 newObject ['a'] = obj ['a'];
和 newObject ['c'] = obj ['c'];
。
MDN [ ^ ]有一个很棒的JS指南和参考资料。
What's happening is you setup a variable which holds all the keys of the obj
parameter - keys
. You then iterate through the arr
parameter checking whether each element (search
) is in the keys
list (indexOf
returns -1 if no key is found). If the element is in the list you then move the value from obj
into newObject
.
The assignment statement given your example will execute newObject['a'] = obj['a'];
and newObject['c'] = obj['c'];
.
The MDN[^] has a great JS guide and reference materials.
这篇关于我想知道这条线上发生了什么,我用粗体。我知道他们的工作,但我不知道为什么。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!