替换javascript数组中的字符串
我有一个javascript数组。此数组具有包含逗号(“,”)的字符串。我希望从此数组中删除所有逗号。可以这样做吗?当然可以--只需迭代数组,并在每次迭代中执行标准删除替换javascript数组中的字符串,javascript,arrays,string,Javascript,Arrays,String,我有一个javascript数组。此数组具有包含逗号(“,”)的字符串。我希望从此数组中删除所有逗号。可以这样做吗?当然可以--只需迭代数组,并在每次迭代中执行标准删除 或者,如果数组的性质允许,可以先将数组转换为字符串,去掉逗号,然后再转换回数组。给定变量s中所需的字符串:- var result = s.replace(/,/g, ''); 对 for(变量i=0;i
或者,如果数组的性质允许,可以先将数组转换为字符串,去掉逗号,然后再转换回数组。给定变量s中所需的字符串:-
var result = s.replace(/,/g, '');
对
for(变量i=0;i
现在最好的方法是以这种方式使用map()
函数:
var resultArr = arr.map(function(x){return x.replace(/,/g, '');});
这是ECMA-262标准。
如果您需要早期版本,可以在项目中添加以下代码:
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
if(!Array.prototype.map)
{
Array.prototype.map=函数(fun/*,thisp*/)
{
var len=此长度;
如果(乐趣的类型!=“功能”)
抛出新的TypeError();
var res=新阵列(len);
var thisp=参数[1];
对于(变量i=0;i
您只需执行以下操作:
array = ["erf,","erfeer,rf","erfer"];
array = array.map(function(x){ return x.replace(/,/g,"") });
现在阵列变为:
[“erf”、“erfeerrf”、“erfer”]
您也可以用更短的语法内联执行
array = array.map(x => x.replace(/,/g,""));
您可以使用
array.map
或forEach
。根据我们的场景,array.map
创建或给定一个新数组forEach
允许您操作已存在数组中的数据。今天我就是这样用的
document.addEventListener("DOMContentLoaded", () => {
// products service
const products = new Products();
// get producsts from API.
products
.getProducts()
.then(products => {
/*
raw output of data "SHEPPERD'S SALLAD" to "SHEPPERDS SALLAD"
so I want to get an output like this and just want the object
to affect the title proporties. other features should stay
the same as it came from the db.
*/
products.forEach(product => product.title = product.title.replace(/'/g,''));
Storage.saveProducts(products);
});
});
在将字符串推入数组之前,不能对其进行筛选吗?否则就是一个简单的for循环,我试过了,但是字符串是动态地从另一个地方来的。但不管怎样,我知道我做错了什么。我在每个db结果后都留下一个逗号。我确信我所做的数组推送是在每次推送之后添加一个逗号。我是JS的新手。无论如何,谢谢。@MannyCalavera,看到我的答案+1比我更接近了,但你需要对结果做点什么,替换不会使字符串发生变异。对不起,kekoav,应该是:arr[i]=arr[i]。替换(/,/g,)??你不需要(读:不应该)自己测试正则表达式,反正这是在幕后发生的。
document.addEventListener("DOMContentLoaded", () => {
// products service
const products = new Products();
// get producsts from API.
products
.getProducts()
.then(products => {
/*
raw output of data "SHEPPERD'S SALLAD" to "SHEPPERDS SALLAD"
so I want to get an output like this and just want the object
to affect the title proporties. other features should stay
the same as it came from the db.
*/
products.forEach(product => product.title = product.title.replace(/'/g,''));
Storage.saveProducts(products);
});
});