문제

I want to convert text strings to numerical values using Javascript in order to create custom variables for a survey link. For example, I have the following possible values for the variable Q14:

Inland Great Lakes Rivers Coastal N/A

How can I convert these text values into numerical valuesso that Inland=1, Great Lakes=2, Rivers=3, Coastal=4, N/A=5?

도움이 되었습니까?

해결책

If you store those values in an array, then you can use indexOf to find the match:

function getLocationNumber(location) {
    var locationOptions = ["Inland", "Great Lakes", "Rivers", "Coastal", "N/A"];
    var locationNumber = locationOptions.indexOf(location) + 1;
    return locationNumber;
}

// Example:
getLocationNumber("Great Lakes") // returns 2
getLocationNumber("Coastal") // returns 3

다른 팁

If you're looking for a C++ solution, here's a similar question and solution: splitting string into array. After you've split it into an array you can use the array index + 1 for the value you're looking for.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top