Javascript对象属性不在范围内

编程入门 行业动态 更新时间:2024-10-20 08:33:41
本文介绍了Javascript对象属性不在范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我似乎对对象的属性范围有疑问.我想将每个Message对象的title和message属性输出到select元素,但这是不起作用!我做错了什么

I seem to have a problem with objects' properties' scope. I would like to output each of the Message objects' title and message properties to a select element, but it is Not Working! What am I doing incorrectly

<html><head> <script type="text/javascript" src="ajax.googleapis/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ function Message(title, message) { this.title=title; this.message=message; this.getTitle = function(){ return this.title; }; this.getMessage = function(){ return this.message; }; } var messages = new Array( new Message("First Title", "This is the first message"), new Message("Second Title", "This is another message") ); function updateSelect () { $("#cannedMessages_button").empty(); for (c in messages) { // First try, with getters and setters $("#cannedMessages_button").append($('<option>', { value : c.getMessage() , text : c.getTitle() })); // Second try, directly $("#cannedMessages_button").append($('<option>', { value : c.message , text : c.title })); } } updateSelect(); }); </script> </head><body> <form><select id="cannedMessages_button"></select></form> </body></html>

我可以验证foreach实际上正在运行两次迭代,但是我无法从对象中获取值.

I can verify that the foreach is in fact running two iterations, but I cannot get the values out of the objects.

推荐答案

不要使用for (c in messages).

in用于迭代对象的属性,而不用于迭代数组中的值.

in is for iterating over properties of an object, not for iterating over values in an array.

使用久经考验的

for(var i = 0; i < messages.length; i++) { ... }

此外,您不会将getTitle和getMessage方法放在原型上,这是一种浪费.

Also, you are not putting your getTitle and getMessage methods on a prototype, which is kind of wasteful.

更多推荐

Javascript对象属性不在范围内

本文发布于:2023-11-13 02:02:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   属性   对象   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!