我正在尝试将其用作函数,我可以在任何字符串上作为函数调用,以获取返回值 true
并使用 .map
以数组形式false
语句 -
我了解.map
的工作原理,并且可以在console.log(lastArray)
时让它在new array
中返回我想要的值,但我无法让它作为我可以调用字符串lastArray(dirtyString)
或finalArray("the cat pop racecar blue")
并得到[false, false, true, true, false]
的函数工作。我不能使用任何循环,必须使用.map
(但我已经解决了这些问题,因为console.log-ing finalArray
为我返回一个新的正确值数组......我只是看不到我做错了什么,当我尝试重新工作时,我得到了Undefined
。我想保持我已有的方法,我只是不知道为什么它不能作为我可以调用的功能(我已经做了几个小时的在线研究,并且已经为此工作了好几天)。另外,对不起,我的代码太混乱了,有时是多余的,而且评论很多(我刚刚尝试了很多方法试图让它工作,我对CS和JS有点陌生)。此外,当尝试对字符串调用函数时,它还会返回错误。这是我的代码:
/* split string into array of substrings, clean out extra spaces, return new array of substrings */
var dirtyString = ("stash and pop on this level");
var cleanArray = function(dirtyString){
var splitString = dirtyString.split(" ");
var cleanArray = splitString.filter(Boolean);
return cleanArray;
};
var newArray = cleanArray(dirtyString);
/* take each element of the array, if it's a palindrome, add a true element to new array using map; if it's not, add a false element to the new array... using map */
///helper function that returns correct value when I console.log it///
var lastArray = newArray.map(function(x) {
if (x === x.split("").reverse().join("")){
return true;}
else {
return false;}
});
*/attempting to put the logic in lastArray into a function I can call /*
var palindromicMap = function (dirtyString) {
var cleanedArray = cleanArray(dirtyString);
var output = cleanedArray.map(function(x){
if (x === x.split("").reverse().join("")){
return true;}
else if (x !== x.split("").reverse().join("")){
return false;}
});
return output;
};
console.log(lastArray);
*/returns correct outcome /*
palidromicMap(cleanArray);
*/returns error /*
palindromicMap("cat pop racecar blue");
*/returns error/*
在这里查看这个 jsfiddle。该函数将字符串作为参数,但你为其提供了函数,从而导致误导性错误消息。
基本上将调用更改为
console.log(palindromicMap(dirtyString));
似乎解决了问题。