仅使用 javascript 逐一打印关联数组元素
我有这段代码
<script type="text/javascript">
var slideStart = 1;
var slideCount = 4;
function callArr() {
var arrName = {"rose":"5", "daisy":"4",
"orchid":"3", "sunFlower":"10",
"Lily":"15"};
for (var flwr in arrName) {
if (slideStart <= slideCount) {
document.getElementById('test').innerHTML += flwr +
" >>>>>>>> " +
arrName[flwr] +
"<br />";
slideStart++;
break;
}
}
}
</script>
,我想在任何事件上单独访问数组元素。有人可以帮我解决这个问题吗???
I have this code
<script type="text/javascript">
var slideStart = 1;
var slideCount = 4;
function callArr() {
var arrName = {"rose":"5", "daisy":"4",
"orchid":"3", "sunFlower":"10",
"Lily":"15"};
for (var flwr in arrName) {
if (slideStart <= slideCount) {
document.getElementById('test').innerHTML += flwr +
" >>>>>>>> " +
arrName[flwr] +
"<br />";
slideStart++;
break;
}
}
}
</script>
I want to access array elements individually on any event. can any please help me out on this????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当然,它只会打印第一个元素,因为您使用这样的条件
修改代码以迭代对象属性。可能的解决方案之一:
在这里尝试:http://jsfiddle.net/2nDv8/
如您所见,它会在每次调用后打印下一个属性。
Of course it will print only the first element since you use condition like this
Modify your code to iterate through the object properties. One of the possible solutions:
Try it here: http://jsfiddle.net/2nDv8/
As you can see, it prints the next property after every call.
如果您引用任何地方的访问,您可以将其声明为 globla var:
另请注意,
break
语句导致仅显示第一个元素希望这会有所帮助。干杯
If you refer to access anywere, you could declare it as globla var:
Also note that the
break
statement was causing to show only the first elementHope this helps. Cheers
这并不完全兼容跨浏览器,但您可以使用
Object.keys(arrName)
。或者,如果您确实关心跨浏览器兼容性,则实际上创建并存储一个行为相同的数组。This isn't exactly cross-browser compatible, but you can use
Object.keys(arrName)
. Or actually create and store an array that acts the same, if you're actually concerned about cross-browser compatibility.它只打印一次,因为您在循环中放置了
"break"
。此代码将毫无问题地打印所有元素。还有一个问题是由slideStart
和slideCount
变量引起的。如果您想打印所有元素,请将slideStart
更改为 0,以便打印所有元素,而不仅仅是其中的 4 个元素。希望有帮助:It only prints once because you put a
"break"
inside your loop. This code will print all elements without problems. One problem is also caused by yourslideStart
andslideCount
variables. If you want to print all of them, changeslideStart
to 0 so that it will print all the elements, not just 4 of those..Hope that helps:也许这就是你想要的。在这里尝试一下:http://jsfiddle.net/Hsn4c/1/
Probably this is what you want. Try it here: http://jsfiddle.net/Hsn4c/1/