Javascript 字符串元素数组上的Javascript映射方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34925609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript map method on array of string elements
提问by Mindi Torrey
I am trying to understand how to implement the map method (rather than using a for loop) to check a string for palindromes and return boolean values for whether the mapped array elements reversed are the same as the original array elements. I cannot seem to understand the syntax of the map method. How do I get the map to function on each element in the original array? What is the value? Here is my working code, which is only logging a value of undefined:
我试图了解如何实现 map 方法(而不是使用 for 循环)来检查回文字符串并返回布尔值,以确定反转的映射数组元素是否与原始数组元素相同。我似乎无法理解 map 方法的语法。如何让地图在原始数组中的每个元素上运行?它的价值是什么?这是我的工作代码,它只记录未定义的值:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
item.split("").reverse().join("");
return newArray === myArray;
});
}
console.log(palindromeChecker("What pop did dad Drink today"));
Here is a link to the fiddle: https://jsfiddle.net/minditorrey/3s6uqxrh/1/
这是小提琴的链接:https: //jsfiddle.net/minditorrey/3s6uqxrh/1/
There is one related question here:
这里有一个相关的问题:
Javascript array map method callback parameters
but it doesn't answer my confusion about the syntax of the map method when using it to perform a function on an array of strings.
但是当使用 map 方法对字符串数组执行函数时,它并没有解决我对 map 方法语法的困惑。
采纳答案by toomanyredirects
The map
method will literally 'map' a function call onto each element in the array, take this as a simple example of increasing the value of each integer in an array by 1:
该map
方法将逐字地将函数调用“映射”到数组中的每个元素,以此作为将数组中每个整数的值增加 1 的简单示例:
var items = [1,2,3];
items.map(function(item) {
return item + 1;
});
// returns [2,3,4]
In your case, you are trying to use map to accept or reject a string if it's a palindrome, so a simple implementation might be:
在您的情况下,您尝试使用 map 来接受或拒绝回文字符串,因此一个简单的实现可能是:
var items = ['mum', 'dad', 'brother'];
items.map(function(item) {
return item.split('').reverse().join('') === item;
});
// returns [true, true, false]
I'm not 100% sure of your reasons for using map
, because if you were trying to just filter the array and remove the strings that aren't palindromes, you should probably use the filter
method instead, which works in the same way, but would remove any that return false:
我不是 100% 确定您使用 的原因map
,因为如果您只是尝试过滤数组并删除不是回文的字符串,您可能应该改用该filter
方法,它的工作方式相同,但会删除任何返回 false 的内容:
var items = ['mum', 'dad', 'brother'];
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['mum', dad']
In your case you are splitting a string first to get your array of characters; you may also want to make that string lower case and remove punctuation, so an implementation might be:
在您的情况下,您首先拆分字符串以获得字符数组;您可能还想让该字符串小写并删除标点符号,因此实现可能是:
var string = 'I live at home with my Mum, my Dad and my Brother!';
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
// returns ['i', 'mum', dad']
As mentioned in one of the comments on your question, you need to ensure you return
a value from your function if you are using a separate function to perform the check, so this is how your function should look:
正如对您的问题的评论之一所述,return
如果您使用单独的函数来执行检查,则需要确保您的函数中有一个值,因此您的函数应如下所示:
function checkPalindromes(string) {
var items = string.toLowerCase().replace(/[^a-z0-9-\s]+/, '').split(' ');
items.filter(function(item) {
return item.split('').reverse().join('') === item;
});
return items;
}
And you would call it using:
您可以使用以下方法调用它:
checkPalindromes('I live at home with my Mum, my Dad and my Brother!'); // ['i', 'mum', 'dad']
回答by Cem Ekici
newArray should include reversed version of theall items in myArray. After that, newArray should be reversed and joined with space in order to get the reversed version of the input string.
newArray 应该包括 myArray 中所有项目的反转版本。之后, newArray 应该被反转并加入空格以获得输入字符串的反转版本。
Here is the code:
这是代码:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.map(function (item) {
return item.split("").reverse().join("");
});
console.log(newArray);
return newArray.reverse().join(" ") === string;
}
console.log(palindromeChecker("dad did what"));
回答by marqn
try something like this:
尝试这样的事情:
let str = 'hello';
let tab = [...str];
tab.map((x)=> {
console.log("|"+x+"|");
return x;
})
回答by DougieHauser
Apart from a few minor mistakes in your code, such as scope issues (you're referencing the "newArray" and "myArray" outside of the function in which they where defined, and therefore, getting "undefined")..
除了代码中的一些小错误,例如范围问题(您在定义它们的函数之外引用了“newArray”和“myArray”,因此获得“未定义”)。
The main issue you had is that you addressed the ENTIRE array inside the map function, while the whole concept is breaking things down to single elements (and then the function collects everything back to an array for you).
您遇到的主要问题是您在 map 函数中处理了整个数组,而整个概念是将事物分解为单个元素(然后该函数为您将所有内容收集回数组)。
I've used the "filter" function in my example, because it works in a similar manner and I felt that it does what you wanted, but you can change the "filter" to a "map" and see what happends.
我在我的示例中使用了“过滤器”功能,因为它以类似的方式工作,我觉得它可以满足您的需求,但是您可以将“过滤器”更改为“地图”并查看发生了什么。
Cheers :)
干杯:)
HTML:
HTML:
<body>
<p id="bla">
BLA
</p>
<p id="bla2">
BLA2
</p>
</body>
Javascript:
Javascript:
function palindromeChecker(string) {
var myString = string.toLowerCase();
var myArray = myString.split(" ");
var newArray = myArray.filter(function (item) {
var reversedItem = item.split('').reverse().join('');
return item == reversedItem;
});
document.getElementById("bla").innerHTML = myArray;
document.getElementById("bla2").innerHTML = newArray;
}
palindromeChecker("What pop did dad Drink today");
回答by Mindi Torrey
Thanks for your input, all. This is the code I ended up with. I fixed the scope issues in the original post. My main problem was understanding the syntax of the map method. In particular, I could not understand from other online resources how to determine the value in the callback function. So, with much help from above I have placed the map method inside the palindromeChecker, and done all of the work on the array inside the map function.
感谢您的投入,所有。这是我最终得到的代码。我修复了原始帖子中的范围问题。我的主要问题是理解 map 方法的语法。特别是,我无法从其他在线资源中了解如何确定回调函数中的值。所以,在上面的很多帮助下,我将 map 方法放在 palindromeChecker 中,并在 map 函数内完成了对数组的所有工作。
var palindromeChecker = function(string) {
var newString = string.toLowerCase().split(' ');
newString.map(function(item) {
console.log(item.split('').reverse().join('') === item);
});
};
palindromeChecker("What pop did dad drink today");
//Returns false, true, true, true, false, false
回答by froginvasion
Mapis a higher-order function available in ES5. I think your newArray
will contain an array of boolean values.
Map是 ES5 中可用的高阶函数。我认为您newArray
将包含一个布尔值数组。
In essence, map will iterate over every value in your array and apply the function. The return value will be the new value in the array. You can also use map and save the information you need somewhere else, and ignore the result of course.
本质上,map 将遍历数组中的每个值并应用该函数。返回值将是数组中的新值。您也可以使用 map 并将您需要的信息保存在其他地方,当然可以忽略结果。
var arr = [1,2,3,4];
var newArray = arr.map(function(i) {
return i * 2;
});
//newArray = [2,4,6,8]
回答by Glubus
The map function in javascript (and pretty much in any language) is a great little function that allows you to call a function on each of the items on a list, and thus changing the list itself. The (anonymous) function you're passing as an argument accepts an argument itself, which is filled by an item of the list it is working on, each time it is called.
javascript 中的 map 函数(以及几乎任何语言中的)是一个很棒的小函数,它允许您对列表中的每个项目调用一个函数,从而更改列表本身。您作为参数传递的(匿名)函数接受一个参数本身,每次调用它时,它都由它正在处理的列表中的一个项目填充。
So for a list [1,2,3,4]
, the function
function(item) { return item + 1 }
, would give you a list of [2,3,4,5]
for a result. The function you passed to $.map()
is run over each element of the list, and thus changing the list.
因此,对于 list [1,2,3,4]
,该函数
function(item) { return item + 1 }
将为您[2,3,4,5]
提供一个结果列表。您传递给的函数$.map()
在列表的每个元素上运行,从而更改列表。
So for your code: in the function you're passing as an argument to $.map()
, you're returning whether the old and new array are equal (which is false btw). So since you're returning a boolean value, the list you'll end up with is a list of bools.
What I think you want to do, is extract the newArray == myArray
from the function you're passing to $.map()
, and putting it after your $.map()
call.
Then inside the function you're passing to $.map()
, return the item you're splitting and whatnot, so your newArray
will be an array of strings like myArray
.
因此,对于您的代码:在您作为参数传递给 的函数中$.map()
,您将返回旧数组和新数组是否相等(顺便说一句,这是错误的)。因此,由于您要返回一个布尔值,因此最终得到的列表是一个布尔值列表。我认为您想要做的是newArray == myArray
从您传递给的函数中提取$.map()
,并将其放在您的$.map()
调用之后。然后在您传递给的函数中$.map()
,返回您要拆分的项目等等,因此您newArray
将是一个字符串数组,例如myArray
.