【问题标题】:Chrome console output of json has weird behaviourjson 的 Chrome 控制台输出有奇怪的行为
【发布时间】:2018-11-10 07:34:52
【问题描述】:
我有一个 json 对象和 2 个 arrays 我正在删除重复的元素。
我想出于测试目的显示之前/之后的更改。
但是一个未知的原因是我的 Chrome 控制台输出没有显示我的数组的所有元素,即使它的长度对应于数组中的元素数。
What I'm expecting vs what I get
如果您想查看代码,请创建JS fiddle。
我的代码结构如下:
//Before------------------
console.log(myjsonobject);
removeduplicates(myjsonobject);
//After-------------------
console.log(myjsonobject);
【问题讨论】:
标签:
javascript
json
google-chrome
duplicates
output
【解决方案1】:
这种行为是预期的,因为 JavaScript 对象作为引用传递,而不是作为值传递的原语。
如果您执行数组的深度克隆,您会看到它打印到控制台就好了..
var createdComponents;
createdComponents = {
"switches":[],
"SA":[]
};
//Adding duplicates elements to my array
createdComponents.switches.push("SW1");
createdComponents.SA.push("SA1");
createdComponents.switches.push("SW1");
createdComponents.SA.push("SA1");
//Display object with duplicates
console.log("Before:------------");
console.log(JSON.parse(JSON.stringify(createdComponents)));
//Removing duplicates
createdComponents.switches = removeDuplicates(createdComponents.switches);
createdComponents.SA = removeDuplicates(createdComponents.SA);
//Display new object
console.log("After duplicates being removed:------------");
console.log(createdComponents);
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
JSFiddle