红宝石般的问题:使此功能更短的(动作3) [英] Ruby-like Question: Make this function shorter (ActionScript 3)

查看:120
本文介绍了红宝石般的问题:使此功能更短的(动作3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚写了这个令人难以置信的详细code打开像2号到02 可以让这个功能更短,请(maintaning的功能)?

I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

	public static function format(n:int, minimumLength:int):String {
		var retVal:String = n.toString();
		var stillNeed:int = minimumLength - retVal.length;
		for (var i:int = 0; i < stillNeed; i++) {
			retVal = "0" + retVal;
		}
		return retVal;
	}

请使用类型变量。加分(好氛围点,没有那么点),如果有已经是一个内置的功能,我不知道。

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

如果有人想发表一些极短的相当于在其他一些语言,这将是一种乐趣。

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

推荐答案

这不会是最快的实现(它做了一些不必要的复制,并具有循环),但它的不错,可读

This wouldn't be the fastest implementation (it does some unnecessary copying and has a loop), but it is nice and readable:

public static function pad(num:int, minLength:uint):String {
    var str:String = num.toString();
    while (str.length < minLength) str = "0" + str;
    return str;
}

这篇关于红宝石般的问题:使此功能更短的(动作3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆