I was having fun with string methods and approached an issue while using slice on a string in the loop:

var sentence = document.querySelector('.newClass').textContent.split(' '),
    blank = '_________________________';

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i); //works
    console.log(sentence[i] + blank.slice(blank.length, sentence[i].length) + i); //???
}

CODE: http://jsfiddle.net/cachaito/Jxzd5/

I was sure string.slice() works same as string.substring()

有帮助吗?

解决方案

There are some subtle differences, most of which are described here. However, the behavior you're seeing is because blank.length is always greater than sentence[i].length, and substring swaps the arguments in this case. From MDN:

If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

But slice doesn't do this. If the first argument is larger than the second, the result will be an empty string (assuming both are positive).

Try this:

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i); //works
    console.log(sentence[i] + blank.slice(sentence[i].length, blank.length) + i); //works
}

Or even this:

for(var i = 0; i < sentence.length; i += 1) {
    console.log(sentence[i] + blank.substring(blank.length, sentence[i].length) + i);
    console.log(sentence[i] + blank.slice(0, -sentence[i].length) + i);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top