Javascript-我和条件斗争

时间:2017-12-03 18:30:45

标签: javascript

  

我需要var x必须只是一个数字而不是文本。

     

我怎么能在条件下写这个?*

2 个答案:

答案 0 :(得分:1)

if (variable.isNaN()) { // it's a string

} else { // It's a number

}

答案 1 :(得分:0)

有很多替代方法,但最简单的方法如下:

第一个解决方案: 使用整数作为变量Feed const voteAction = (framework) => { return { type: "VOTE", payload: framework } } const updateCurrentPercentages = (voteState) => { return { type: "UPDATE_CURRENT_PERCENTAGES", payload: voteState } } export const castVote = (framework) => (dispatch, getState) => { dispatch(voteAction(framework)); dispatch(updateCurrentPercentages(getState().votes)); //this does pass in current vote state correctly } 如果你export function currentPercentageReducer(state=intitialPercentages, action){ switch (action.type){ case "UPDATE_CURRENT_PERCENTAGES": let totalVotes = action.payload.angular + action.payload.react + action.payload.vue; //totalVotes, and individual percentage calculations are //all console.logged correctly. //EX. if there is one vote for each of the three frameworks //I get totalVotes = 3, pctAngular = 1/3, pctReact = 1/3, //pctVue = 1/3 console.log('totalVotes', totalVotes) console.log('pctAngular', action.payload.angular + ' / ' + totalVotes); console.log('pctReact', action.payload.react + ' / ' + totalVotes); console.log('pctVue', action.payload.vue + ' / ' + totalVotes); let pctAngular = Math.floor(action.payload.angular / totalVotes) * 100; let pctReact = Math.floor(action.payload.react / totalVotes) * 100; let pctVue = Math.floor(action.payload.vue / totalVotes) * 100; //as soon as I vote for two or more different options //the console.log below always returns 0,0,0 console.log(pctAngular, pctReact, pctVue); //returns the correct state when you only vote for one //option, but when you vote for two or more returns // {angular:0, react:0, vue:0} return Object.assign({}, state, { angular: pctAngular, react: pctReact, vue: pctVue }); default: return state } } ,你会看到结果是12(整数),而不是字符串

第2个解决方案: 只需使用var x = 12; EXP:

console.log(x)

结果与上面的结果相同

如果你需要检查变量是一个数字:

parseInt()

如果您需要字符串变量中的提取编号,请进行一些搜索。 问候