【JavaScript】01数组原型对象的最后一个元素、计数器

题目一:数组原型对象的最后一个元素

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1 。

你可以假设数组是 JSON.parse 的输出结果。

示例 1 :

输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

输入:nums = []
输出:-1
解释:因为此数组没有元素,所以应该返回 -1。
提示:
  • arr 是一个有效的 JSON 数组
  • 0 <= arr.length <= 1000
/**
 * @return {null|boolean|number|string|Array|Object}
 */
Array.prototype.last = function() {
    
};

/**
 * const arr = [1, 2, 3];
 * arr.last(); // 3
 */

解题:

方法一:

Array.prototype.last = function() {
    if(this.length===0){
        return -1;
    }else{
       return this[this.length-1] 
    }
    
};

方法二:

Array.prototype.last = function() {
  return this.length === 0 ? -1 : this[this.length - 1];
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/array-prototype-last/solutions/2506895/shu-zu-yuan-xing-dui-xiang-de-zui-hou-yi-4phe/
来源:力扣(LeetCode)

题目二:计数器

给定一个整型参数 n,请你编写并返回一个 counter 函数。这个 counter 函数最初返回 n,每次调用它时会返回前一个值加 1 的值 ( n ,  n + 1 ,  n + 2 ,等等)。

示例 1:

输入:
n = 10 
["call","call","call"]
输出:[10,11,12]
解释:
counter() = 10 // 第一次调用 counter(),返回 n。
counter() = 11 // 返回上次调用的值加 1。
counter() = 12 // 返回上次调用的值加 1。

示例 2:

输入:
n = -2
["call","call","call","call","call"]
输出:[-2,-1,0,1,2]
解释:counter() 最初返回 -2。然后在每个后续调用后增加 1。

提示:

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

解题:

方法一:

function createCounter(n) {  
    let count = n; // 初始化计数值为 n  
    return function() {  
        return count++; // 返回当前计数值,并同时将其递增  
    };  
} 

方法二:

var createCounter = function(n) {
  return function() {
    return n++;      
  };
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/counter/solutions/2487678/ji-shu-qi-by-leetcode-solution-xuwj/
来源:力扣(LeetCode)

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值