从underscore.js转换为vanilla javascript

时间:2018-03-14 04:26:36

标签: javascript underscore.js

我在Underscore.js中遇到过这段代码,我想将其转换为vanilla javascript。关于如何做到这一点的任何想法?

var makeLetters = function(word) { 
      return _.map(word.split(''), function(character) {
      return { name: character, chosen: false };
    }); 

这是上面函数的当前输出,我想保留相同的结构,除了我想在常规的javascript中完成这个。

0: {name: "s", chosen: false, $$hashKey: "003"}
1: {name: "c", chosen: false, $$hashKey: "004"}
2: {name: "o", chosen: false, $$hashKey: "005"}
3: {name: "p", chosen: false, $$hashKey: "006"}
4: {name: "e", chosen: false, $$hashKey: "007"}

3 个答案:

答案 0 :(得分:2)



// Your current Underscore code:
/*
var makeLetters = function(word) { 
  return _.map(word.split(''), function(character) {
  return { name: character, chosen: false };
});
*/

// New ES6+ code:
const makeLetters = (word) => word.split('').map(character => ({ name: character, chosen: false }));

// If you aren't using ES6+:
var makeLetters = function(word) {
  return word.split('')
    .map(function(character) {
      return { name: character, chosen: false };
    });
};




答案 1 :(得分:0)



        var makeLetterWord="scope";
        var makeLettersSplit = makeLetterWord.split('').map(function(character) {
              return { name: character, chosen: false };
            });
           
console.log(makeLettersSplit );




答案 2 :(得分:-1)

在ES 2015 +

function makeLetters(word) {
    return word.split('').map(v => { name: v, chosen: false });
}

在ES 5之前

function makeLetters(word) {
    return word.split('').map(function(v) {
        return { name: v, chosen: false };
    });
}