wes*_*yth 22 javascript arrays underscore.js
我正在尝试使用纯JS重新创建Underscore pluck函数.但是,我一直在返回一个未定义的数组,而不是数组中对象属性的实际值.
在这里检查另一个线程我发现你可以使用以下代码在jQuery中重现它...
$.pluck = function(arr, key) {
return $.map(arr, function(e) { return e[key]; })
}
Run Code Online (Sandbox Code Playgroud)
...但是我很难在纯JS中再现它.我尝试了以下内容,但这只是为我返回一个undefined数组.
var pluck = function(arr,key){
var newArr = [];
for (var i = 0, x = arr.length; i < x; i++){
if (arr[i].hasOwnProperty(key)){
newArr.push(arr[i].key)
}
}
return newArr;
}
Run Code Online (Sandbox Code Playgroud)
因此,目标将是以下,除了使用下划线_.pluck,只需使用JS函数名称,例如.var pluck = function(arr,key){...}
var Tuts = [{name : 'NetTuts', niche : 'Web Development'}, {name : 'WPTuts', niche : 'WordPress'}, {name : 'PSDTuts', niche : 'PhotoShop'}, {name : 'AeTuts', niche : 'After Effects'}];
var niches = _.pluck(Tuts, 'niche');
console.log(niches);
// ["Web Development", "WordPress", "PhotoShop", "After Effects"]
Run Code Online (Sandbox Code Playgroud)
有人能引导我朝正确的方向发展吗?
Gil*_*tel 35
在ES5中:
function pluck(array, key) {
return array.map(function(obj) {
return obj[key];
});
}
Run Code Online (Sandbox Code Playgroud)
在ES6中:
function pluck(array, key) {
return array.map(o => o[key]);
}
Run Code Online (Sandbox Code Playgroud)
Poi*_*nty 14
您可以使用本机JavaScript执行此操作.map()
:
Array.prototype.pluck = function(key) {
return this.map(function(object) { return object[key]; });
};
Run Code Online (Sandbox Code Playgroud)
编辑 - 修改内置原型对象应该小心; 一个更好的方法来添加函数(如果您对一般这样做的想法没有问题)将会Object.defineProperty
使它成为不可枚举的:
Object.defineProperty(Array.prototype, "pluck", {
value: function(key) {
return this.map(function(object) { return object[key]; });
}
});
Run Code Online (Sandbox Code Playgroud)
你是如此亲密.你需要改变:
newArr.push(arr[i].key);
Run Code Online (Sandbox Code Playgroud)
至:
newArr.push(arr[i][key]);
Run Code Online (Sandbox Code Playgroud)
考虑一下:
var obj = { myKey: 'my Value', theKey: 'another value' };
var theKey = 'myKey';
alert(obj.theKey); // another value
alert(obj[theKey]); // my Value
// You can also send in strings here:
alert(obj['theKey']); // another value
Run Code Online (Sandbox Code Playgroud)
希望你明白我的观点.
归档时间: |
|
查看次数: |
24847 次 |
最近记录: |