简体   繁体   English

在JavaScript中查找和替换数组中字符串的改进方法

[英]Improved Method of Finding and replacing Strings in an Array in Javascript

I have the following array: 我有以下数组:

["cat", "dog", "cow"] 

I want to replace the values of each with a new string. 我想用一个新的字符串替换每个值。

["tiger", "wolf", "diary"]

Currently I am traversing through a for loop and checking to see if a string that needs its name to be changed exists, if it does then I am replacing it with the new value. 当前,我正在遍历for循环,并检查是否存在需要更改其名称的字符串,如果存在,则将其替换为新值。 While a for loop works, I am wondering if there's a nicer way of doing this. 虽然for循环有效,但我想知道是否有更好的方法可以做到这一点。

Assuming you have an object with the replacing to do, you can use Array.map 假设您有一个要替换的对象,则可以使用Array.map

 var replace = { 'cat': 'tiger', 'dog': 'wolf', 'cow': 'diary', }; var starter = ["cat", "dog", "cow"]; var final = starter.map(value => replace[value] || value); console.log(final) 

If the string is not in the replace object, replace[value] is undefined , so replace[value] || value 如果字符串不在replace对象中,则replace[value]undefined ,因此replace[value] || value replace[value] || value is evaluet do value itself. replace[value] || value就是value本身。

Anyway, the for is definitely more performing, at least on node.js, accordingly to benchmark.js: 无论如何, for肯定至少在node.js上相对于Benchmark.js表现更好:

Array.map x 2,818,799 ops/sec ±1.90% (76 runs sampled)
for array x 9,549,635 ops/sec ±1.86% (79 runs sampled)
Fastest is for array

Here the code I used for the test 这是我用于测试的代码

var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;

suite
.add('Array.map', function() {
  var replace = {
    'cat': 'tiger',
    'dog': 'wolf',
    'cow': 'diary',
  };

  var starter = ["cat", "dog", "cow"];

  var final = starter.map(value => replace[value] || value);
})
.add('for array', function() {
  var replace = {
    'cat': 'tiger',
    'dog': 'wolf',
    'cow': 'diary',
  };

  var starter = ["cat", "dog", "cow"];

  var final = [];

  for (var i = 0; i < starter.length; i++) {
    final.push(replace[starter[i]] || starter[i]);
  }
})
// add listeners
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
function transform(str){
   //logic to transform goes here
}

var massaged = myArr.map(transform);

Maybe thats what youre asking for? 也许这就是您要的?

map reference here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 此处的地图参考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM