在 Javascript 中返回一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14076448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a string in Javascript
提问by tree
I am trying to create a simple function that will return the correct string when called:
我正在尝试创建一个简单的函数,该函数在调用时将返回正确的字符串:
function getState(abbr){
if (abbr=="WY")
{
return "Wyoming";
}
}
and then the call is like this:
然后电话是这样的:
var stateName = getState("WY");
However all that is getting returned is: 0
然而,所有返回的是:0
Sorry if I am missing something obvious.
对不起,如果我遗漏了一些明显的东西。
UPDATE - my orig prob was because of a "&" here's the real code I'm dealing with:
更新 - 我的原始问题是因为“&”这是我正在处理的真实代码:
function getState(abbr){
var url = "states.asp"
var state = "";
$.get(url, function(data) {
var i = 0;
$.each($('state',data),function(index, el) {
if (abbr == ($(this).attr("abbr"))){
//alert($(this).attr("abbr"));
state = $(this).text();
}//if (abbr == $(this).attr("abbr")){
});//$.each($('state',data),function(index, el) {
}).success(function() {
alert("x" + state);
return state;
}); //.success(function() {
//$.get(url, function(data) {
alert("y" + state);
return state;
}
I am getting "undefined" as a result to my call:
由于我的电话,我得到“未定义”:
alert(getState("WY"));
Alert("x" + state) works.
Alert("x" + state) 有效。
UPDATE #2 --- here is all that states.asp generates (for now)... later it will return companies, etc:
更新 #2 --- 这是 states.asp 生成的所有内容(目前)...稍后它将返回公司等:
<?xml version="1.0" encoding="utf-8"?>
<STATELIST>
<STATE abbr="AL">Alabama</STATE>
<STATE abbr="AK">Alaska</STATE>
<STATE abbr="AZ">Arizona</STATE>
<STATE abbr="AR">Arkansas</STATE>
<STATE abbr="CA">California</STATE>
<STATE abbr="CO">Colorado</STATE>
<STATE abbr="CT">Connecticut</STATE>
<STATE abbr="DE">Delaware</STATE>
<STATE abbr="FL">Florida</STATE>
<STATE abbr="GA">Georgia</STATE>
<STATE abbr="HI">Hawaii</STATE>
<STATE abbr="ID">Idaho</STATE>
<STATE abbr="IL">Illinois</STATE>
<STATE abbr="IN">Indiana</STATE>
<STATE abbr="IA">Iowa</STATE>
<STATE abbr="KS">Kansas</STATE>
<STATE abbr="KY">Kentucky</STATE>
<STATE abbr="LA">Louisiana</STATE>
<STATE abbr="ME">Maine</STATE>
<STATE abbr="MD">Maryland</STATE>
<STATE abbr="MA">Massachusetts</STATE>
<STATE abbr="MI">Michigan</STATE>
<STATE abbr="MN">Minnesota</STATE>
<STATE abbr="MS">Mississippi</STATE>
<STATE abbr="MO">Missouri</STATE>
<STATE abbr="MT">Montana</STATE>
<STATE abbr="NE">Nebraska</STATE>
<STATE abbr="NV">Nevada</STATE>
<STATE abbr="NH">New Hampshire</STATE>
<STATE abbr="NJ">New Jersey</STATE>
<STATE abbr="NM">New Mexico</STATE>
<STATE abbr="NY">New York</STATE>
<STATE abbr="NC">North Carolina</STATE>
<STATE abbr="ND">North Dakota</STATE>
<STATE abbr="OH">Ohio</STATE>
<STATE abbr="OK">Oklahoma</STATE>
<STATE abbr="OR">Oregon</STATE>
<STATE abbr="PA">Pennsylvania</STATE>
<STATE abbr="RI">Rhode Island</STATE>
<STATE abbr="SC">South Carolina</STATE>
<STATE abbr="SD">South Dakota</STATE>
<STATE abbr="TN">Tennessee</STATE>
<STATE abbr="TX">Texas</STATE>
<STATE abbr="UT">Utah</STATE>
<STATE abbr="VT">Vermont</STATE>
<STATE abbr="VA">Virginia</STATE>
<STATE abbr="WA">Washington</STATE>
<STATE abbr="WV">West Virginia</STATE>
<STATE abbr="WI">Wisconsin</STATE>
<STATE abbr="WY">Wyoming</STATE>
</STATELIST>
采纳答案by Beetroot-Beetroot
Easiest approach is to make a hash - no function needed.
最简单的方法是进行散列 - 不需要函数。
var states = {
'AL': 'Alabama',
'AK': 'Alaska',
'AZ': 'Arizona',
'AR': 'Arkansas',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
...
'WY': 'Wyoming'
};
var stateName = states["WY"];
EDIT
编辑
Now I better understand that getState()needs to retrieve State names from the server. This puts you into the world of asynchronous coding, which is quite different from normal, synchronous coding.
现在我更好地理解getState()需要从服务器检索状态名称。这会将您带入异步编码的世界,这与正常的同步编码完全不同。
The most important thing to realise is that getState()can't simply return a state name for a given state abbreviation. Why? Because the ajax call to the server is asynchronous- in other words getState()won't wait for the server's response before returning.
要意识到的最重要的事情是getState()不能简单地为给定的州缩写返回州名。为什么?因为对服务器的 ajax 调用是异步的——换句话说getState(),在返回之前不会等待服务器的响应。
There are essentially two approaches to handling asynchronicity :
处理异步性基本上有两种方法:
- pass callback function(s) to
getState()to tell it what to do when a response is received - arrange for
getState()to return a special type of object called a "promise" which can be handled wheregetState()is called, in such a way that it will respond when the server has responded.
- 传递回调函数
getState()来告诉它在收到响应时要做什么 - 安排
getState()返回一种称为“承诺”的特殊类型的对象,它可以在getState()被调用的地方处理,这样它就会在服务器响应时做出响应。
The code below adopts the second approach.
下面的代码采用了第二种方法。
var states = {};//cache of state names, with state abbreviations as keys
function getState(abbr) {
var dfrd = $.Deferred();//A deferred object, whose promise will be returned.
if(!states[abbr]) {
$.ajax({
url: "states.asp",
dataType: 'XML',
success: function(data) {
//Load up the cache
$.each($('state', data), function(i, el) {
states[el.attr('abbr')] = $(el).text();
});
//Now resolve or reject the deferred object depending in whether states[abbr] has been cached
if(states[abbr]) {
dfrd.resolve(abbr, states[abbr]);//Success! Let's resolve the deferred object (and its promise).
}
else {
dfrd.reject(abbr, 'States successfully downloaded but ' + abbr + ' was not included');
}
},
error: function() {
dfrd.reject(abbr, 'Download of states failed');
}
});
}
else {
//The state name is already cached
//The deferred object (and its promise) can be resolved without needing to make another ajax call.
dfrd.resolve(abbr, states[abbr]);
}
return dfrd.promise();
}
untested
未经测试
Now all you need to know is how to call getState().
现在您只需要知道如何调用getState().
getState("WY").done(function(abbr, state) {
alert(abbr + ': ' + state);
//other stuff here
}).fail(function(abbr, message) {
alert(abbr + ': ' + message);
//other stuff here
});
As you can see, the value that you wanted getState()to return now appears as the second argument of a .done()function. For good measure, the abbreviation ("WY") appears as the first argument.
如您所见,您想要getState()返回的值现在显示为.done()函数的第二个参数。为了更好地衡量,缩写(“WY”)作为第一个参数出现。
If you want to handle error conditions (always a good idea), then do so in a .fail()callback.
如果你想处理错误情况(总是一个好主意),那么在.fail()回调中这样做。
See comments in code for more clues as to how everything works.
有关一切如何工作的更多线索,请参阅代码中的注释。
回答by Paul Fleming
There is absolutely nothing broken in your code. See this working demo.
您的代码中绝对没有任何问题。请参阅此工作演示。
function getState(abbr){
if (abbr=="WY")
{
return "Wyoming";
}
}
var stateName = getState("WY");
alert(stateName);
?
回答by Ali Mohammadi
HTML:
HTML:
<div id="msg">...</div>
JS:
JS:
function getState(abbr){
if (abbr=="WY")
{
return "Wyoming";
}
}
var stateName = getState("WY");
?document.getElementById('msg').innerHTML=stateName;
回答by frenchie
That's going to be a lot of ifstatements to evaluate: the function would potentially have to go through all 50 ifstatements to get to Wyoming! I'd rewrite it with a switchstatement, like that:
这将需要if评估很多语句:该函数可能必须通过所有 50 条if语句才能到达怀俄明州!我会用这样的switch语句重写它:
function getState(abbr){
switch case(abbr) {
case "WY":
return "Wyoming";
...
}
}
I think this should be faster. I would also add a defaultcase, just in case the input is bad.
我认为这应该更快。我还会添加一个default案例,以防万一输入不好。
回答by tree
This is just my solution. I'm still grabbing at straws trying to understand asynch behaviour, but here's what worked:
这只是我的解决方案。我仍然试图理解异步行为,但这是有效的:
Instead of:
代替:
function searchServing(which,choice){
var state = getState("WY");
$("#searchResults").html("<tr><td>" + state + "</td></tr>");
.get(function() {
} //for reference call this getSearchServing
}
i had to reverse the call so:
我不得不撤回电话,所以:
function getState(abbr){
.get(function(){
$("#searchResults").html("<tr><td>" + state + "</td></tr>");
})
.success(function() {
searchServing('serving',abbr);
})
}
still not sure why getSearchServing would run before getState and not sure why I couldn't return a value from getState ???
仍然不确定为什么 getSearchServing 会在 getState 之前运行,并且不确定为什么我不能从 getState 返回值???

