【发布时间】:2021-03-20 04:45:03
【问题描述】:
现在我正在编写代码作为处理数据的一种测试。我使用的数组比我实际要处理的数组短,我遇到了麻烦,我想我知道出了什么问题,但这有点像脑放屁,我实际上找不到问题。感谢您提供任何帮助,因此在此先感谢您。
if (!Object.prototype.hasOwnProperty('log')) {
Object.defineProperty(Object.prototype, 'log', {
get: function() {
console.log(this);
}
});
}
if (!Object.prototype.hasOwnProperty('getProps')) {
Object.defineProperty(Object.prototype, 'getProps', {
get: function() {
//console.log(Object.getOwnPropertyNames(this));
return Object.getOwnPropertyNames(this);
}
});
}
function appendItem(list, item) {
list.push(item);
}
var cities = ["Houston", "Dallas", "Rockwall", "Bossier", "Shreveport"];
var dates = ["monday", "monday", "monday", "monday", "monday"];
var states = ["Texas", "Texas", "Texas", "Louisiana", "Louisiana"];
function Setup(obj, sub, thisArg) {
obj.forEach(function(key, index) {
if ((this[key] == undefined)) {
this[key] = [sub[index]];
} else {
appendItem(this[key], sub[index]);
}
}, thisArg);
return obj;
}
var weather = {};
Setup(dates, states, weather);
weather.log;
Setup(states, cities, weather);
weather.log;
我想要的结果是可以做到这一点的:
weather = {monday:{Texas:["Houston", "Dallas", "Rockwall"], Louisiana:["Bossier", "Shreveport"]}};
但是以循环或函数的形式,因为当我弄清楚这一点时我将使用的实际数据要大得多。这是我得到的实际输出:
if (!Object.prototype.hasOwnProperty('log')) {
Object.defineProperty(Object.prototype, 'log', {
get: function() {
console.log(this);
}
});
}
if (!Object.prototype.hasOwnProperty('getProps')) {
Object.defineProperty(Object.prototype, 'getProps', {
get: function() {
//console.log(Object.getOwnPropertyNames(this));
return Object.getOwnPropertyNames(this);
}
});
}
function appendItem(list, item) {
list.push(item);
}
var cities = ["Houston", "Dallas", "Rockwall", "Bossier", "Shreveport"];
var dates = ["monday", "monday", "monday", "monday", "monday"];
var states = ["Texas", "Texas", "Texas", "Louisiana", "Louisiana"];
function Setup(obj, sub, thisArg) {
obj.forEach(function(key, index) {
if ((this[key] == undefined)) {
this[key] = [sub[index]];
} else {
appendItem(this[key], sub[index]);
}
}, thisArg);
return obj;
}
var weather = {};
Setup(dates, states, weather);
weather.log;
Setup(states, cities, weather);
weather.log;
【问题讨论】:
标签: javascript arrays javascript-objects nested-object