javascript - 删除对象属性上的逗号

标签 javascript jquery

我试图在获取对象属性时去掉逗号,但在获取名称时我总是得到它。这是我尝试过的:

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);

我总是明白这一点

enter image description here

或者这个

enter image description here

这里是FIDDLE

那么如何打印出没有逗号的干净名称呢?

最佳答案

您的问题结果是Array#toString()如何工作:nullundefined值被转换为空字符串,并且数组是用“,”连接:

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/

相关文章:

javascript - ng-container Angular 9 Flex 布局无法读取未定义 fxFlex 问题的属性 'setProperty'

javascript - 有没有办法检查是否强制执行严格模式?

javascript - v-for 中的未知属性使用 Vue

javascript - 如果验证失败则禁用提交按钮

javascript - 更改 HTML 行中单元格的索引

javascript - 是否可以将javascript注入(inject)到使用ajax调用后加载的dom中?

javascript - 如何为输入标签分配一些值

javascript - 将混合数据类型数组从 php 传递到 javascript 数组

jQuery jsonp 自动完成不可见的下拉项

javascript - 从ie7中的输入获取图像的base64?