gpt4 book ai didi

javascript 匿名函数的变量作用域

转载 作者:行者123 更新时间:2023-12-02 17:01:09 25 4
gpt4 key购买 nike

我有一个 javascript/jquery 函数,其中我将 div 内的每个元素存储到数组中。问题是它不会将结果保存在匿名函数之外。如何设置全局变量?

这是我的 Javascript/jquery

function store_options(){
var stored_options = new Array;
$('[id^="tagboxfv-"]').each(function(){
var last_index = slice_last_index(this);
$('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
stored_options[last_index] = [];
stored_options[last_index][$(this).val()]=$(this);
});
});
}

最佳答案

一般来说,不建议在 JavaScript 中使用全局变量。但是如果您仍然想使用它,只需将其定义在函数范围之外即可:

var stored_options = new Array;

function store_options(){
$('[id^="tagboxfv-"]').each(function(){
var last_index = slice_last_index(this);
$('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
stored_options[last_index] = [];
stored_options[last_index][$(this).val()]=$(this);
});
});
}

作为替代方案,您的函数可以有一个 return 语句,这样您就可以在任何您想要的地方使用它(这样就不会引入全局变量):

function store_options(){  
var stored_options = new Array;
$('[id^="tagboxfv-"]').each(function(){
var last_index = slice_last_index(this);
$('[id="form-'+last_index+'"] > select[id="v-'+last_index+'"] > option').each(function(){
stored_options[last_index] = [];
stored_options[last_index][$(this).val()]=$(this);
});
return stored_options;
});
}

关于javascript 匿名函数的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25707804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com