我无法让它作为 JavaScript 函数工作(我在控制台时得到我想要的返回值.log但我不能将其作为函数调用)
I can't get this to work as a JavaScript function (I get the return value I want when I console.log this but I can't call it as a function)
我正在尝试将其用作函数,我可以在任何字符串上作为函数调用,以获取返回值 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));
似乎解决了问题。
相关文章:
- 在多行图表中,在每一行的末尾,我想要一个小圆圈和使用d3.js的端点值
- 我想要相同的函数以两种方式反应
- 如何格式化我返回的url,使其符合我想要的路由
- 为什么获胜't我的javascript返回我想要的值
- 通过 javascript 将值从子页面返回到父页面时面临的问题.它正在返回对象,我想要值
- 当我想要设置对象属性时,输入中的未定义值
- .attr('class') 返回多个类名,如何选择我想要使用的类名
- 我无法让它作为 JavaScript 函数工作(我在控制台时得到我想要的返回值.log但我不能将其作为函数调用)
- 我想要Ember.js'{{input value=“searchTerm”}}以将其值设置为''
- 获取[object object]在javascript中,当我想要的值
- ObjectToQuery函数返回只是属性值,但我想要所有的属性
- 当定义一个函数时,为什么我需要返回一个函数而不是直接返回我想要的值?
- Q.all返回异步函数,而不是我想要解析的值
- 如何在javascript中获得上传文件的完整路径.它总是返回c:fakepath.我想要servlet的完整路径
- 我如何检查数据表是否包含我想要的值,并可能单击链接
- 我想要HTML搜索栏与5个值,当值显示image1,也喜欢值2显示image2
- 文档.getElementById不返回null,但也不做我想要的.javascript控制台没有错误
- .off('单击')-但我想要'单击'再次返回
- 我想要每个单独的返回值从reduce()函数,而不是总数
- 元素.height返回可见高度-我想要total