admin管理员组文章数量:1394124
I'm attempting to write a JavaScript function to determine if all letters in a string are in alphabetical order. The following would keep returning "SyntaxError: Unexpected token default"
function orderedWords(str) {
var s=str.toLowerCase().split("");
for(var i=0; i<s.length; i++) {
var default = s[i];
if (s[i+1] >= default)
default = s[i+1];
else return false;
}
return true;
}
orderedWords("aaabcdefffz"); // true
orderedWords("abcdefzjjab"); // false
Any help is much appreciated.
I'm attempting to write a JavaScript function to determine if all letters in a string are in alphabetical order. The following would keep returning "SyntaxError: Unexpected token default"
function orderedWords(str) {
var s=str.toLowerCase().split("");
for(var i=0; i<s.length; i++) {
var default = s[i];
if (s[i+1] >= default)
default = s[i+1];
else return false;
}
return true;
}
orderedWords("aaabcdefffz"); // true
orderedWords("abcdefzjjab"); // false
Any help is much appreciated.
Share Improve this question edited Feb 20, 2015 at 3:17 Henry asked Feb 20, 2015 at 2:27 HenryHenry 2792 gold badges4 silver badges13 bronze badges 02 Answers
Reset to default 7default
is a keyword in JavaScript, and cannot be a variable name.
EDIT: Also, you have a logic issue: if you iterate up to length
, in your last iteration you will check the last character against undefined
; the test will fail, and you will return false
. Rewrite into:
for(var i=0; i<s.length - 1; i++) {
EDIT2: I am not actually even sure why you're using that variable, since it has no bearing to the rest of your code. This should work as well (also, I moved the range from [0..length-1)
to [1..length)
for easier calculation):
function orderedWords(str) {
var s=str.toLowerCase().split("");
for(var i=1; i<s.length; i++) {
if (s[i - 1] > s[i]) {
return false;
}
}
return true;
}
EDIT3: Simpler, shorter:
function orderedWords(str) {
return str == str.split('').sort().join('');
}
It looks like you're looking for more than a sort? With this function you can use any letter order defined in map, and also the function removes punctuation just in case you need to check messy strings.
var map = "abcdefghijklmnopqrstuvwxyz";
function orderedWords(str,map){
str = str.replace(/(.)(?=.*\1)/g, "");
str = str.replace(/\W/g, '');
var test = ""
for(var i in map){
if(str.indexOf(map[i])>-1){
test += map[i];
}
}
if(test.toLowerCase() == str.toLowerCase()){
return true;
}
return false;
}
console.log(orderedWords("aaabcdefffz", map));
console.log(orderedWords("abcdefzjjab", map));
本文标签: arraysDetermine if all letters in a string are in alphabetical order JavaScriptStack Overflow
版权声明:本文标题:arrays - Determine if all letters in a string are in alphabetical order JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744773320a2624474.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论