我知道,这很奇怪!但为什么这不起作用?
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = subString.slice(counter);
}
return counter;
}
var output = getStringLength('hello');
console.log(output); // --> expecting 5, but getting 3 (??)
我真的想用切片来做!最初的挑战是不使用长度属性,我想出来了,这很好用:
function getStringLength(string) {
var long = 0;
while (string[long] !== undefined) {
long++;
}
return long;
}
答案 0 :(得分:6)
你正在改变你的字符串,这应该适合你
function getStringLength(string) {
// see how many substrings > 0 can be built
// log that number & return
var subString = string.slice();
var counter = 0;
while (subString !== '') {
counter++;
subString = subString.slice(1);
}
return counter;
}
var output = getStringLength('hello');
console.log(output); // 5

主要区别在于我在做什么
subString = subString.slice(1);
而不是
subString = subString.slice(counter);
总是将长度减少1
答案 1 :(得分:4)
问题是代码import App from './App';
import Home from './Home';
import Contact from './Contact';
import About from './About';
ReactDOM.render( (
<Router history = {history}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "/home" component = {Home} />
<Route path = "/about" component = {About} />
<Route path = "/contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'));
第一次,你砍掉1个字符。然后你从已经被砍掉的子串中砍下2个字符。要么一次切断1个,要么从原始字符串中切断增加的量。那就是substring.slice(counter)
或substring.slice(1)
string.slice(counter)
&#13;
答案 2 :(得分:1)
要达到预期效果,请使用以下选项
function getStringLength(arr){
return arr.lastIndexOf(arr.slice(-1))+1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/gGPWEE?editors=1111
选项2:由于数组类型为object,因此下面的选项也适用
function getStringLength(arr){
return Object.keys(arr).pop()*1 + 1
}
var output = getStringLength('hello');
console.log(output);
https://codepen.io/nagasai/pen/PJZmgg?editors=1111
检查以下更新的选项以处理空和数字
https://codepen.io/nagasai/pen/GMoQgy?editors=1111
https://codepen.io/nagasai/pen/YrweWr?editors=1111
答案 3 :(得分:0)
也许是一个稍微简短的回答:
dat <- structure(list(Group = c(1L, 1L, 1L, 2L, 2L, 3L), ID = c("A",
"A", "B", "A", "B", "C")), .Names = c("Group", "ID"), class = "data.frame", row.names = c(NA,
-6L))
&#13;