我试图在获取对象属性时去掉逗号,但在获取名称时我总是得到它。这是我尝试过的:
var items = [{ "id": "1", "name": "ball" }, { "id": "2", "name": "galaxy" }];
var getName = items.map(function(element){
if (element.id == 2){
return element.name.replace(',', '');
}
});
alert(getName);
我总是明白这一点
或者这个
这里是FIDDLE
那么如何打印出没有逗号的干净名称呢?
最佳答案
您的问题结果是Array#toString()
如何工作:null
和undefined
值被转换为空字符串,并且数组是用“,”连接:
var names = [undefined, "galaxy"];
console.log("names (array):", names);
console.log("names (string):", String(names));
alert(names)
强制 names
转换为字符串,因为 alert()
只能打印字符串。最好使用控制台。
我不确定你是想打印一个名字还是所有名字,你的代码对我来说不明确。
var items = [{ "id": "1", "name": "ball" }, { "id": "2", "name": "galaxy" }];
//since you're using `map` it implies that you want
//to fetch the name of every item in the array
//because this is what `Array#map()` does.
function getAllNames(){
return items.map(item => item.name);
}
console.log("all names:", getAllNames(items));
//on the other hand, your condition would imply you want only a specific item
function getNameById(id){
return items.find(item => item.id === id).name;
}
console.log("name of #1:", getNameById("1"));
console.log("name of #2:", getNameById("2"));
还有一件事。您已将变量命名为 getName
,这对我来说意味着它包含一个可以执行以获取名称的函数。但事实并非如此。它包含一个带有名称和未定义
值的数组。
变量和函数的正确命名有助于理解代码特定部分的情况;不仅对我们来说,而且如果您必须在两周后再次查看该代码。
关于javascript - 删除对象属性上的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780374/