输出未定义。我看不到代码有什么问题,可能有点小..有什么帮助吗?输入123,预期输出321。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="demo">
<nav>
<div class="menu-icon">
<i class="fa fa-bars fa-2x"></i>
</div>
<div class="logo">
<img src="img/logo.png" alt="LOGO">
</div>
<div class="menu">
<ul class="menuul">
<li><a href="">Home</a></li>
<li><a href="">Menu#2</a></li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li><a href="">Menu#3</a></li>
<li><a href="">Menu#4</a></li>
</ul>
</div>
</nav>
</div>
</body>
</html>
答案 0 :(得分:0)
您犯了三个错误:
x
的整数推到stack
,将char推到该索引。number
初始设置为''
而非undefined
var reverse = function(x) {
x = String(x)
var stack=[];
var number = '';
for(var i =0;i<x.length;i++){
stack.push(x[i])
}
while(stack.length >0){
number += stack.pop();
}
return +number;
};
console.log(reverse(123))
我认为最好将数字转换为字符串数组,然后循环遍历该数组的一半以将其反转。最后使用join()
var reverse = function(x) {
x = String(x).split('');
for(let i = 0;i<Math.floor(x.length/2);i++){
let temp = x[i];
x[i] = x[x.length - i - 1];
x[x.length - i - 1] = temp;
}
return x.join('')
};
console.log(reverse(123))
当您不想使用reverse()
时,以上代码是最好的。使用reverse()
,您可以制作单线纸
var reverse = x => +String(x).split('').reverse().join('')
console.log(reverse(123))
答案 1 :(得分:0)
使用扩展运算符...
拆分字符串(在这种情况下,等效于s.split('')
)。 reverse
数组,然后使用join('')
连接。
const reverse = (s) => {
let isNumber = typeof s === 'number'
if (isNumber) s += ''; // Convert to string
let result = [...s].reverse().join('');
return isNumber ? parseInt(result) : result;
}
console.log(reverse(123));
编辑:处理数字和字符串