这是我在https://dartpad.dev上尝试过的简单的Dart代码。
void main(){
var numbers = new List(10);
for(int i=0; i<=10; i++){
numbers[i] = i;
}
print(numbers[1]);
print("hello world");
}
为什么控制台为空?它不打印1
或hello world
。此代码有什么问题?
最佳答案
您的代码有一个index out of range error
,也就是说,当您使用i<=10
时,您会得到它。
- Since, in your initialization of the
List numbers
, you have the length as10
, but due toi<=10
, it will store the length of11
. Hence error.- The code will go from
0,1,2,3,4,5,6,7,8,9,10
, which is in total11
in number. INDEX OUT OF RANGE ERROR
Uncaught Error: RangeError (index): Index out of range: index should be less than 10: 10
如果您不希望出现错误,则只需要按以下方式创建数据:i<10
。否则,请使用i=1; i<11
=> 1,2,3,4,5,6,7,8,9,10
void main(){
var numbers = new List(10);
for(int i=0; i<10; i++){
numbers[i] = i;
}
print(numbers[1]);
print("hello world");
}
输出1
hello world
关于dart - 为什么即使在打印字符时控制台也为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63337260/